package com.cqie.hospitalescort.service.login.UserDetailService;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cqie.hospitalescort.DTO.AuthUser;
import com.cqie.hospitalescort.entity.AdminUser;
import com.cqie.hospitalescort.enums.LoginTerminalEnum;
import com.cqie.hospitalescort.mapper.AdminUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import static com.cqie.hospitalescort.service.login.UserDetailService.WxUserDetailServiceImpl.getAuthorities;

/**
 * 管理员浏览器系统端
 */
@Service
public class AdminUserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private AdminUserMapper adminUserMapper;

    /**
     * 加载管理员信息
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public AuthUser loadUserByUsername(String username) throws UsernameNotFoundException {
        if (username.startsWith(LoginTerminalEnum.BROWSER.getCode())) {
            username = username.substring((LoginTerminalEnum.BROWSER.getCode() + "_").length());
        }
        AdminUser adminUser = adminUserMapper.selectOne(new LambdaQueryWrapper<AdminUser>().eq(AdminUser::getUsername, username));
        if (null == adminUser) {
            throw new UsernameNotFoundException(username);
        }
        AuthUser authUser = new AuthUser();
        authUser.setUsername(adminUser.getUsername());
        authUser.setPassword(adminUser.getPassword());
        authUser.setRole(adminUser.getRole());
        authUser.setCreateTime(adminUser.getCreateTime());
        authUser.setAuthorities(getAuthorities(adminUser.getRole()));
        return authUser;
    }
}
